// library.js (修改后)
let booksData = [];
let currentUser = null;
let users = {};
let bookStatistics = {};

function initializeLibrary(data) {
    booksData = data.books || [];
    
    // 初始化书籍统计
    booksData.forEach(book => {
        bookStatistics[book.title] = {
            borrowCount: 0,
            currentBorrows: 0,
            waitingList: []
        };
    });
    
    console.log('Library initialized with', booksData.length, 'books');
}

function loginUser(username) {
    if (!username) return false;
    
    if (!users[username]) {
        users[username] = {
            borrowedBooks: [],
            credits: 3,
            waitingBooks: []
        };
        console.log('New user registered:', username);
    }
    
    currentUser = username;
    return true;
}

function getCurrentUser() {
    return currentUser ? users[currentUser] : null;
}

function searchBooks(query) {
    if (!query || !booksData) return [];
    
    const lowerQuery = query.toLowerCase();
    return booksData.filter(book => {
        return (
            book.title.toLowerCase().includes(lowerQuery) ||
            (book.authors && book.authors.some(author => 
                author.toLowerCase().includes(lowerQuery))) ||
            (book.year && book.year.toString().includes(query))
        );
    });
}

function borrowBook(bookTitle) {
    if (!currentUser) return { success: false, message: '请先登录' };
    
    const user = users[currentUser];
    const book = booksData.find(b => b.title === bookTitle);
    const stats = bookStatistics[bookTitle];
    
    if (!book) return { success: false, message: '图书不存在' };
    if (user.credits <= 0) return { success: false, message: '您的信用分不足，无法借书' };
    if (book.number_of_copies <= 0) return { success: false, message: '图书已全部借出' };
    if (user.borrowedBooks.includes(bookTitle)) return { success: false, message: '您已借阅此书' };
    if (user.borrowedBooks.length >= 7) return { success: false, message: '借阅数量已达上限(7本)' };
    
    book.number_of_copies--;
    user.borrowedBooks.push(bookTitle);
    stats.borrowCount++;
    stats.currentBorrows++;
    
    // 检查是否在等待列表中
    const waitIndex = stats.waitingList.indexOf(currentUser);
    if (waitIndex > -1) {
        stats.waitingList.splice(waitIndex, 1);
        user.waitingBooks = user.waitingBooks.filter(title => title !== bookTitle);
    }
    
    return { success: true, message: `成功借阅《${bookTitle}》` };
}

function returnBook(bookTitle) {
    if (!currentUser) return { success: false, message: '请先登录' };
    
    const user = users[currentUser];
    const book = booksData.find(b => b.title === bookTitle);
    const stats = bookStatistics[bookTitle];
    
    if (!book) return { success: false, message: '图书不存在' };
    if (!user.borrowedBooks.includes(bookTitle)) return { success: false, message: '您未借阅此书' };
    
    book.number_of_copies++;
    user.borrowedBooks = user.borrowedBooks.filter(title => title !== bookTitle);
    stats.currentBorrows--;
    
    // 检查是否有等待者
    if (stats.waitingList.length > 0 && book.number_of_copies > 0) {
        const nextUser = stats.waitingList.shift();
        borrowBook(bookTitle, nextUser);
    }
    
    return { success: true, message: `成功归还《${bookTitle}》` };
}

function reportLost(bookTitle) {
    if (!currentUser) return { success: false, message: '请先登录' };
    
    const user = users[currentUser];
    const book = booksData.find(b => b.title === bookTitle);
    
    if (!book) return { success: false, message: '图书不存在' };
    if (!user.borrowedBooks.includes(bookTitle)) return { success: false, message: '您未借阅此书' };
    
    // 扣除信用分
    user.credits--;
    user.borrowedBooks = user.borrowedBooks.filter(title => title !== bookTitle);
    
    return { 
        success: true, 
        message: `已报告《${bookTitle}》丢失，信用分扣除1分，当前信用分: ${user.credits}` 
    };
}

function joinWaitingList(bookTitle) {
    if (!currentUser) return { success: false, message: '请先登录' };
    
    const user = users[currentUser];
    const book = booksData.find(b => b.title === bookTitle);
    const stats = bookStatistics[bookTitle];
    
    if (!book) return { success: false, message: '图书不存在' };
    if (book.number_of_copies > 0) return { success: false, message: '图书仍有库存，无需等待' };
    if (user.waitingBooks.includes(bookTitle)) return { success: false, message: '您已在等待列表中' };
    if (user.borrowedBooks.includes(bookTitle)) return { success: false, message: '您已借阅此书' };
    
    stats.waitingList.push(currentUser);
    user.waitingBooks.push(bookTitle);
    
    return { success: true, message: `您已加入《${bookTitle}》的等待列表` };
}

function getBorrowedBooks() {
    if (!currentUser || !users[currentUser]) {
        console.error('用户未登录或不存在');
        return [];
    }
    return users[currentUser].borrowedBooks || [];
}

function getPopularBooks(limit = 5) {
    return Object.entries(bookStatistics)
        .sort((a, b) => b[1].borrowCount - a[1].borrowCount)
        .slice(0, limit)
        .map(([title, stats]) => ({
            title,
            borrowCount: stats.borrowCount,
            currentBorrows: stats.currentBorrows,
            waitingCount: stats.waitingList.length
        }));
}

function getUserWaitingList() {
    if (!currentUser) return [];
    return users[currentUser].waitingBooks;
}

window.initializeLibrary = initializeLibrary;
window.loginUser = loginUser;
window.getCurrentUser = getCurrentUser;
window.searchBooks = searchBooks;
window.borrowBook = borrowBook;
window.returnBook = returnBook;
window.reportLost = reportLost;
window.joinWaitingList = joinWaitingList;
window.getPopularBooks = getPopularBooks;
window.getUserWaitingList = getUserWaitingList;